from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from apps.model.crud import create_register_user, login_verify_user
from apps.utils.depends import get_db
from apps.model.schames import RegisterUserIn, LoginUserIn
from fastapi_jwt_auth import AuthJWT


router = APIRouter()


# class RegisterUserIn(BaseModel):
#     """注册 输入模型"""
#     username: str = Field(..., max_length=50, min_length=3)
#     password: str = Field(..., max_length=16, min_length=6)
#     email: Optional[str] = Field(None, max_length=64)
#



# async def get_db():
#     # 1、创建数据库连接对象
#     db = SessionLocal()
#     try:
#         # 2、返回数据库连接对象，注入到路径操作装饰器 / 路径操作函数 / 其他依赖项
#         yield db
#     finally:   # 确保后面的代码一定会执行
#         # 3、用完之后再关闭
#         db.close()


@router.post('/register')
def register_user(body: RegisterUserIn, db: Session = Depends(get_db)):
    """注册接口"""
    print(f"用户输入的参数：{body}")   # pydantic 对象
    print(f"用户输入的参数：{body.dict()}")
    create_register_user(db, body)
    return {"msg": "注册成功"}


@router.post('/login')
def login_user(body: LoginUserIn, db: Session = Depends(get_db), Authorize: AuthJWT = Depends()):
    """登录接口"""
    print(f"用户输入的参数：{body}")  # pydantic 对象
    obj = login_verify_user(db, body)
    # 登录后 返回token
    another_claims = {"is_admin": 1, "email": obj.email, 'user_id': obj.id}
    access_token = Authorize.create_access_token(subject=body.username, user_claims=another_claims)
    return {"msg": "登录成功", "access_token": access_token}